<%@ page language="java" import="java.util.*" pageEncoding="utf-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ page language="java" import="java.io.BufferedReader" %>
<%@ page language="java" import="java.io.FileReader" %>
<%@ page language="java" %>
<%@ page import="java.text.*" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
    String webSocketPath = request.getServerName() + ":" + request.getServerPort() + path;
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
    <base href="<%=basePath%>">
    <meta charset="UTF-8">
    <title>WebGL模型页面</title>

    <%--热力图模型--%>

    <link rel="stylesheet" type="text/css" href="mintor/compensatormanage/js/webuploader.css"/>

    <script type="text/javascript" src="jquery/jquery-easyui-1.4.3/jquery.min.js"></script>
    <%--<script type="text/javascript" src="jquery/jquery.form.js"></script>--%>

    <script type="text/javascript" src="mintor/model/threeJs/dat.gui.min.js"></script>
    <script type="text/javascript" src="mintor/model/threeJs/three.js"></script>
    <script type="text/javascript" src="mintor/model/threeJs/Detector.js"></script>
    <script type="text/javascript" src="mintor/model/threeJs/OrbitControls.js"></script>
    <script type="text/javascript" src="mintor/model/threeJs/VRMLLoader.js"></script>
    <script type="text/javascript" src="mintor/model/threeJs/stats.min.js"></script>
    <script type="text/javascript" src="mintor/model/threeJs/Tween.js"></script>
    <script type="text/javascript" src="mintor/model/threeJs/RequestAnimationFrame.js"></script>

    <script type="text/javascript" src="mintor/compensatormanage/js/webuploader.js"></script>

    <style>
        body {
            margin: 0;
            overflow: hidden;
            background-color: #AAAAFF;
        }

        .lbl {
            color: #fff;
            font-size: 15px;
            font-weight: bold;
            position: absolute;
            z-index: 100;
            text-shadow: #000 1px 1px 1px;
            background-color: rgba(0, 0, 0, 0.85);
            padding: 1em
        }

        #lbl_tip {
            text-align: left;
        }

        .g {
            color: #aaa
        }

        .c {
            color: orange
        }

    </style>
</head>


<body>


<%--机床页面左上角的内容--%>
<%--<div id = "left" style="background:blue;width:626px;height: 100%;float: left;margin-top: 60px;">--%>
<div id="lbl_tip" class="lbl" style="display: none;">
    <p2 id="sensorNum"><span class="c">传感器编号: 001-SDT00-04</span><br/></p2>
    <p2 id="sensorValue">数值: <span class="c">28.5度</span><br/></p2>
</div>


<div id="legend" style="font-size:1px;font-family:SimSun;position: absolute; width:60px;height:240px;top:200px;right:180px;"></div>



<script type="text/javascript">

    if (!Detector.webgl) Detector.addGetWebGLMessage();
    var controls;                                           // 鼠标响应控制变量
    var picControl = 0;
    var container, scene, webGLRenderer, camera;
    var webglRenderWidth, webglRenderHeight;    //渲染器画布大小
    var maxis, columnaxis, xaxismotion, yaxismotion, zaxismotion, totalMd, sensor, raycaster, mouse;

    var geom = new THREE.Geometry(), line, splineHelperObjects = [];   //定义线条全局变量


    var orimaxisposition, orix, oriy, oriz, currentx, currenty, currentz; //设置原始标记坐标


    var machineMotion;                              // 机床动作组
    var maxisGroup = undefined;                     // 主轴动作组
    var maxisBase = {x: 0, y: 1.25, z: 0};                 // 主轴基准坐标
    var maxisDeviation = {x: 0, y: 0, z: 0};               // 主轴初始化后偏移
    var axisBase = {x: 0, y: 0, z: 0};                // 三轴基准坐标
    var maxisOrigin = {x: 0, y: 0, z: 0};                  // 主轴原始坐标
    var runStatus = false, xdir = false, zdir = false, ydir = false;
    var maxiGroupRotateSpeed = 0;                    // 主轴旋转速度
    var mode_sel_v = 0, axis_sel_v = 0, rate_sel_v = 0;         // 模式选择，轴选择与倍率选择变量

    var socketPath = "<%=webSocketPath%>";
    var postionarr, xaxis, yaxis, zaxis, mspeed;
    var temdata = 0;
    var temdatas = "";
    var temMap = new Dictionary();//存放websocket传来的数据(json格式)
    var webSocket = new WebSocket('ws://' + socketPath + '/websocket/CFlower');

    webSocket.onerror = function (event) {			// socket错误响应事件
        onError(event);
    };
    webSocket.onopen = function (event) {			// socket开启响应事件
        onOpen(event);
    };
    webSocket.onmessage = function (event) {		// socket接收响应事件
        temdatas = event.data;
        onMessage(event);

        //将websocket传来的数据转成json格式
        var temObjects = JSON.parse(temdatas, function (k, v) {
            //JSON.parse(text [, reviver])将字符串转成json对象
            //text一个有效的 JSON 字符串
            //reviver一个转换结果的函数,将为对象的每个成员调用此函数。

            //v取FBG值，在20-100之间
            if (v != "0" & v != "" & v != null & typeof(v) == 'string') {
                if (v.indexOf('/') >= 0) {
                    // var start = v.indexOf('/') + 1;
                    var end=v.indexOf('/');
                    v = v.substring(0,end);
                    if(v!="0"& v != "" & v != null){//防止FBG温度值为0(无效值)
                        temMap.set(k, v);
                    }
                }
                else {
                    temMap.set(k, v);
                }
            }
            // console.log(temMap.getItems());
        });

        heatMapFun(6,13,"Z");//Z轴
        heatMapFun(3,14,"X");//右立柱
        heatMapFun(4,15,"X");//左立柱




    };


    init();
    render();

    $(document).ready(function(){
        $.ajax({
            url: "dataStarting",
            type: "get"
        });
    })

    $(window).resize(function () {
        webGLRenderer.setSize(window.innerWidth, window.innerHeight);
    });


    function init() {
//        var stats = initStats();                                // 初始化帧数显示插件
//         oRight=document.getElementById('right');
//         oRight.appendChild(container);//把上面的层放到right里

//         定义渲染器的初始大小
        webglRenderWidth = window.innerWidth;
        webglRenderHeight = window.innerHeight;

        container = document.createElement('div');
        document.body.appendChild(container);


        webGLRenderer = new THREE.WebGLRenderer({antialias: true});      // 生成渲染对象并设置抗锯齿为有效
        webGLRenderer.setPixelRatio(window.devicePixelRatio);
        webGLRenderer.setClearColor(0xaaaaff, 1.0);                            // 设置canvas背景色(clearColor)
        webGLRenderer.setSize(webglRenderWidth, webglRenderHeight);     // 指定渲染的宽高
        webGLRenderer.shadowMap.enabled = true;
        container.appendChild(webGLRenderer.domElement);


        scene = new THREE.Scene();      //定义场景
        camera = new THREE.PerspectiveCamera(60, webglRenderWidth / webglRenderHeight, 0.01, 1e10);
        camera.position.set(-8, 3, -0.2);//-8, 3, -0.2
        scene.add(camera);

        /** 轨道控制器OrbitControls.js是一个用户交互插件，可以实现场景用鼠标交互，让场景动起来，
         * 控制场景的旋转（左键）、平移（右键）、缩放（滚轮）
         * 利用当前摄像机建立鼠标控制
         * 新建一个轨道控制器后，就要让它实时工作和更新，一般写在渲染和动画的函数里面
         */
        controls = new THREE.OrbitControls(camera);

        //坐标轴辅助
        // var axes = new THREE.AxisHelper(100);
        // scene.add(axes);

        var dirLight = new THREE.DirectionalLight(0xffffff);  //方向光
        dirLight.position.set(130,150,1000).normalize();//130/150/1000
        camera.add(dirLight);
        camera.add(dirLight.target);

        var objLoader = new THREE.VRMLLoader();
        objLoader.load('mintor/model/model_heatmap.wrl', function (geometry) {
            geometry.position.set(0, 0, 0);
            scene.add(geometry);

            sensor = geometry;

            // xaxismotion = new Array(sensor.children[3]);                  // X轴运动块数组
            // yaxismotion = new Array(sensor.children[3].children[5]);      // Y轴运动块数组
            // zaxismotion = new Array(                                      // Z轴运动块数组
            //     sensor.children[3].children[5].children[2],
            //     sensor.children[3].children[5].children[3],
            //     sensor.children[3].children[5].children[4],
            //     sensor.children[3].children[5].children[5] ,
            //     sensor.children[3].children[5].children[6]
            // );
            // machineMotion = new Array(xaxismotion, yaxismotion, zaxismotion);             // 机床运动块数组
            //
            // maxis = sensor.children[3].children[5].children[6].children[7]; //VIFS17

            // var part=geometry.children[0].children[0].children[3].children[5].children[6].children[14];
            // var gradient1 = new gradientColor('#00FF00', '#FFFF00', 1000);
            // var gradient2 = new gradientColor('#FFFF00', '#FF0000', part.children.length-1000);
            //
            // for(var i= 0;i<part.children.length;i++){
            //     if(i<1000){
            //         part.children[i].children[0].material.color.set(gradient1[i]);
            //     }
            //     else{
            //         part.children[i].children[0].material.color.set(gradient2[i-1000]);
            //     }
            // }


        });


    }


    function onMouseDownzaxis(event) {
        //THREE.Raycaster射线，用于鼠标拾取（计算出鼠标移过的三维空间中的对象）
        raycaster = new THREE.Raycaster();
        mouse = new THREE.Vector2();
        event.preventDefault();                                                    // 禁用事件的默认处理程序

        //将鼠标点击位置的屏幕坐标转成threejs中的标准坐标
        mouse.x = (event.clientX / webglRenderWidth) * 2 - 1;                       // 计算鼠标坐标
        mouse.y = -(event.clientY / webglRenderHeight) * 2 + 1;

        raycaster.setFromCamera(mouse, camera);                                   // 设置射线，射线的起点是照相机，终点是鼠标点击的点

        var intersects = raycaster.intersectObjects(sensor.children, true);       //检查射线和物体之间的所有交叉点（true表示其包含后代）
        var intersected;
        if (intersects.length > 0) {                                              // 是否拾取到物体
            intersected = intersects[0].object;      //选中第一个射线相交的物体
            if (intersected) {
                var throughBoxArray = intersects[0].object.matrixWorld.elements.toString();

                for (var i = 1; i < 91; i++) {
                    var zaxissensor = sensor.children[3].children[5].children[6].children[6].children[i];//VIFS16，Z轴上的传感器
                    if (throughBoxArray == zaxissensor.children[0].matrixWorld.elements.toString()) {
                        container.style.cursor = 'pointer';
                        zaxissensor.scale.set(3, 1.5, 2);
                        zaxissensor.children[0].children[0].material.color.set(0xff0000);

                        /*document.getElementById("lbl_tip").style.left = event.clientX + 10 + "px";
                         document.getElementById("lbl_tip").style.top = event.clientY + "px";*/
                        getData(event, temdatas, zaxissensor.name);

                        /*document.getElementById("sensorNum").innerHTML = "<p2 id='sensorNum'>传感器编号: <span class='c'>001-SDT00-" + zaxissensor.name + "</span><br/></p2>";
                         document.getElementById("sensorValue").innerHTML = "<p2 id='sensorValue'>数值: <span class='c'> " + temdata+ "度</span><br/></p2>";
                         $('#lbl_tip').show();*/
                        break;
                    }
                    else {
                        container.style.cursor = 'auto';
                        document.getElementById("lbl_tip").style.display = "none";
                        sensor.children[3].children[5].children[6].children[6].children[i].scale.set(1, 1, 1);
                        sensor.children[3].children[5].children[6].children[6].children[i].children[0].children[0].material.color.set(0x00ffff);

                        //左下方传感器，VIFS01
                        if (i < 31 && throughBoxArray == sensor.children[0].children[i].children[0].matrixWorld.elements.toString()) {
                            var xleftsensor = sensor.children[0].children[i];
                            container.style.cursor = 'pointer';
                            xleftsensor.scale.set(3, 1.5, 2);
                            xleftsensor.children[0].children[0].material.color.set(0xff0000);
                            /* document.getElementById("lbl_tip").style.left = event.clientX + 10 + "px";
                             document.getElementById("lbl_tip").style.top = event.clientY + "px";*/
                            getData(event, temdatas, xleftsensor.name);
                            /*document.getElementById("sensorNum").innerHTML = "<p2 id='sensorNum'>传感器编号: <span class='c'>001-SDT00-" + xleftsensor.name + "</span><br/></p2>";
                             document.getElementById("sensorValue").innerHTML = "<p2 id='sensorValue'>数值: <span class='c'> " + i + "度</span><br/></p2>";
                             $('#lbl_tip').show();*/
                            break;
                        } else if (i < 31) {
                            sensor.children[0].children[i].scale.set(1, 1, 1);
                            sensor.children[0].children[i].children[0].children[0].material.color.set(0x00ffff);
                        }

                        //右下方传感器，VIFS02
                        if (i < 31 && throughBoxArray == sensor.children[1].children[i].children[0].matrixWorld.elements.toString()) {
                            var xrightsensor = sensor.children[1].children[i];
                            container.style.cursor = 'pointer';
                            xrightsensor.scale.set(3, 1.5, 2);
                            xrightsensor.children[0].children[0].material.color.set(0xff0000);
                            /*document.getElementById("lbl_tip").style.left = event.clientX + 10 + "px";
                             document.getElementById("lbl_tip").style.top = event.clientY + "px";*/
                            getData(event, temdatas, xrightsensor.name);
                            /*document.getElementById("sensorNum").innerHTML = "<p2 id='sensorNum'>传感器编号: <span class='c'>001-SDT00-" + xrightsensor.name + "</span><br/></p2>";
                             document.getElementById("sensorValue").innerHTML = "<p2 id='sensorValue'>数值: <span class='c'> " + i + "度</span><br/></p2>";
                             $('#lbl_tip').show();*/
                            break;
                        } else if (i < 31) {
                            sensor.children[1].children[i].scale.set(1, 1, 1);
                            sensor.children[1].children[i].children[0].children[0].material.color.set(0x00ffff);
                        }

                        //左立侧传感器，VIFS25
                        if (i < 25 && throughBoxArray == sensor.children[3].children[4].children[i].children[0].matrixWorld.elements.toString()) {
                            var coleftsensor = sensor.children[3].children[4].children[i];
                            container.style.cursor = 'pointer';
                            coleftsensor.scale.set(3, 1.5, 2);
                            coleftsensor.children[0].children[0].material.color.set(0xff0000);
                            /*document.getElementById("lbl_tip").style.left = event.clientX + 10 + "px";
                             document.getElementById("lbl_tip").style.top = event.clientY + "px";*/
                            getData(event, temdatas, coleftsensor.name);
                            /*document.getElementById("sensorNum").innerHTML = "<p2 id='sensorNum'>传感器编号: <span class='c'>001-SDT00-" + coleftsensor.name + "</span><br/></p2>";
                             document.getElementById("sensorValue").innerHTML = "<p2 id='sensorValue'>数值: <span class='c'> " + i + "度</span><br/></p2>";
                             $('#lbl_tip').show();*/
                            break;
                        } else if (i < 25) {
                            sensor.children[3].children[4].children[i].scale.set(1, 1, 1);
                            sensor.children[3].children[4].children[i].children[0].children[0].material.color.set(0x00ffff);
                        }

                        //右立侧传感器，VIFS24
                        if (i < 25 && throughBoxArray == sensor.children[3].children[3].children[i].children[0].matrixWorld.elements.toString()) {
                            var corightsensor = sensor.children[3].children[3].children[i];
                            container.style.cursor = 'pointer';
                            corightsensor.scale.set(3, 1.5, 2);
                            corightsensor.children[0].children[0].material.color.set(0xff0000);
                            /*document.getElementById("lbl_tip").style.left = event.clientX + 10 + "px";
                             document.getElementById("lbl_tip").style.top = event.clientY + "px";*/
                            getData(event, temdatas, corightsensor.name);
                            /*document.getElementById("sensorNum").innerHTML = "<p2 id='sensorNum'>传感器编号: <span class='c'>001-SDT00-" + corightsensor.name + "</span><br/></p2>";
                             document.getElementById("sensorValue").innerHTML = "<p2 id='sensorValue'>数值: <span class='c'> " + i + "度</span><br/></p2>";
                             $('#lbl_tip').show();*/
                            break;
                        } else if (i < 25) {
                            sensor.children[3].children[3].children[i].scale.set(1, 1, 1);
                            sensor.children[3].children[3].children[i].children[0].children[0].material.color.set(0x00ffff);
                        }
                        //横梁传感器，VIFS05
                        if (i < 21 && throughBoxArray == sensor.children[3].children[2].children[i].children[0].matrixWorld.elements.toString()) {
                            var yaxissensor = sensor.children[3].children[2].children[i];
                            container.style.cursor = 'pointer';
                            yaxissensor.scale.set(3, 1.5, 2);
                            yaxissensor.children[0].children[0].material.color.set(0xff0000);

                            /*document.getElementById("lbl_tip").style.left = event.clientX + 10 + "px";
                             document.getElementById("lbl_tip").style.top = event.clientY + "px";*/
                            getData(event, temdatas, yaxissensor.name);
                            /*document.getElementById("sensorNum").innerHTML = "<p2 id='sensorNum'>传感器编号: <span class='c'>001-SDT00-" + yaxissensor.name + "</span><br/></p2>";
                             document.getElementById("sensorValue").innerHTML = "<p2 id='sensorValue'>数值: <span class='c'> " + i + "度</span><br/></p2>";
                             $('#lbl_tip').show();*/
                            break;
                        } else if (i < 21) {
                            sensor.children[3].children[2].children[i].scale.set(1, 1, 1);
                            sensor.children[3].children[2].children[i].children[0].children[0].material.color.set(0x00ffff);
                        }

                    }
                }
            }
        }
        else {
            container.style.cursor = 'auto';
        }

        var intersectsm = raycaster.intersectObjects(maxis.children, true);
        var intersectedm;
        if (intersectsm.length > 0) {                                              // 是否拾取到物体
            intersectedm = intersectsm[0].object;
            if (intersectedm) {
                var throughBoxArraym = intersectsm[0].object.matrixWorld.elements.toString();
                //主轴传感器，VIFS17
                for (var i = 1; i < 13; i++) {
                    if (throughBoxArraym == maxis.children[i].children[0].matrixWorld.elements.toString()) {
                        var maxissensor = maxis.children[i];
                        container.style.cursor = 'pointer';
                        maxissensor.scale.set(3, 1.5, 2);
                        maxissensor.children[0].children[0].material.color.set(0xff0000);
                        getData(event, temdatas, maxissensor.name);
                        break;
                    } else {
                        maxis.children[i].scale.set(1, 1, 1);
                        maxis.children[i].children[0].children[0].material.color.set(0x00ffff);
                    }
                }
            }
        }
    }


    var poswebSocket = new WebSocket('ws://' + socketPath + '/websocket/001-POS');

    poswebSocket.onerror = function (event) {			// socket错误响应事件
        onError(event);
    };
    poswebSocket.onopen = function (event) {			// socket开启响应事件
        onOpen(event);
    };
    poswebSocket.onmessage = function (event) {		// socket接收响应事件
        // var data = JSON.parse(event.data);
        // if (data.value != "0.0" && data.value != "0,0,0,0" && data.value != "") {
        //     var temvalue = data.value.toString();
        //     postionarr = temvalue.split(",");
        //     xaxis = parseFloat(postionarr[0]);
        //     yaxis = parseFloat(postionarr[1]);
        //     zaxis = parseFloat(postionarr[2]);
        //     mspeed = parseFloat(postionarr[3]);
        //     moveGrouptoRealPosition(machineMotion[0], 0, (-2500 - xaxis) * 3 / 2500);
        //     moveGrouptoRealPosition(machineMotion[1], 1, (2000 + yaxis) * 3 / 2000);
        //     moveGrouptoRealPosition(machineMotion[2], 2, zaxis * 1.3 / 650);
        //     document.getElementById("xpos").innerHTML = "<p2 id='xpos'>x轴坐标：<span class='c'>" + xaxis.toFixed(4) + "</span><br/></p2>";
        //     document.getElementById("ypos").innerHTML = "<p2 id='ypos'>y轴坐标：<span class='c'>" + yaxis.toFixed(4) + "</span><br/></p2>";
        //     document.getElementById("zpos").innerHTML = "<p2 id='zpos'>z轴坐标：<span class='c'>" + zaxis.toFixed(4) + "</span><br/></p2>";
        //     document.getElementById("maspd").innerHTML = "<p2 id='maspd'>主轴转速：<span class='c'>" + mspeed.toFixed(4) + "</span><br/></p2>";
        onMessage(event);
        // }
    };


    function onOpen(event) {
    }

    function onError(event) {
        alert(event.data);
    }

    function onMessage(event) {
        // console.log(event.data);
    }

    function getData(event, temdatas, name) {//"001-SFT00-11":"47.43","001-SFT00-12":"39.33/20.18",

        var str = name;
        var str1 = str.replace(/_/g, '-');
        var realname = str1.substring(1);
        var start = temdatas.indexOf(realname);   //根据传感器名字查找其在字符串中开始位置
        if (start > 0) {
            var end = temdatas.indexOf(",", start + 15);         //查找数据结束位置
            temdata = temdatas.substring(start + 15, end - 1);
        } else {
            temdata = "0";
        }
        // document.getElementById("lbl_tip").style.left = event.clientX + 10 + "px";
        // document.getElementById("lbl_tip").style.top = event.clientY + "px";
        // document.getElementById("sensorNum").innerHTML = "<p2 id='sensorNum'><span class='c'>传感器: " + name + "</span><br/></p2>";
        if (temdata.indexOf("/") > 0) {
            temdata = temdata.substring(0, temdata.indexOf("/"));
        }
        return temdata;
    }

    function onMouseDownR(event) {
        if (event.button == 1) {                        // 滚轮键
            xdir = !xdir;
        }
        if (event.button == 0) {                        // 左键
            ydir = !ydir;
        }
        if (event.button == 2) {                        // 右键
            zdir = !zdir;
        }
    }
    ;


    function initAxisGrouptoPosition(tempGroup, taxis, pos) {
        for (var iTem in tempGroup) {
            switch (taxis) {
                case 0:
                    tempGroup[iTem].position.x = pos;
                    break;           // x轴移动到目的位置
                case 1:
                    tempGroup[iTem].position.z = pos;
                    break;           // y轴移动到目的位置
                case 2:
                    tempGroup[iTem].position.y = pos;
                    break;           // z轴移动到目的位置
                default:
                    break;
            }

        }
    }

    function initAllAxisGroup() {                                       // 机床三轴根据主轴偏移初始化函数
        initAxisGrouptoPosition(machineMotion[0], 0, axisBase.x);   //前后，后为+
        initAxisGrouptoPosition(machineMotion[1], 1, axisBase.z);    //左右，右为+
        initAxisGrouptoPosition(machineMotion[2], 2, axisBase.y);   //上下，上为+
    }


    function render(times) {

        if (runStatus == true) {
            if (maxisGroup != undefined) {
                rotatyMaxisGroupPosition(maxiGroupRotateSpeed);
                maxisGroup.zoomSpeed = 1.2;
            }
            if (xaxismotion != undefined) {
                moveGroupPositionX(machineMotion[0]);                  // 移动x轴块
                moveGroupPositionY(machineMotion[1]);                  // 移动y轴块
                moveGroupPositionZ(machineMotion[2]);                  // 移动z轴块
            }
        }
        if (maxisGroup != undefined) infoShowChange();
        requestAnimationFrame(render);       //以合适的时间间隔执行render()方法，通常是60次每秒
        TWEEN.update(times);
        controls.update();
        webGLRenderer.render(scene, camera);

    }

    //定义字典类型的增删改查
    function Dictionary() {
        var items = {};

        this.has = function (key) {
            return key in items;
        };

        this.set = function (key, value) {
            items[key] = value;
        };

        this.remove = function (key) {
            if (this.has(key)) {
                delete items[key];
                return true;
            }
            return false;
        };

        this.get = function (key) {
            return this.has(key) ? items[key] : 0;
        };

        this.keys = function () {
            var keys = [];
            for (var k in items) {
                if (this.has(k)) {
                    keys.push(parseInt(k));
                }
            }
            return keys;
        };

        this.values = function () {
            var values = [];
            for (var k in items) {
                if (this.has(k)) {
                    values.push(parseFloat(items[k]));
                }
            }
            return values;
        };

        this.clear = function () {
            items = {};
        };

        this.size = function () {
            var count = 0;
            for (var prop in items) {
                if (items.hasOwnProperty(prop)) {
                    ++count;
                }
            }
            return count;
        };

        this.getItems = function () {
            return items;
        };
    }

    //渐变色,输入#000000,返回#000000格式
    function gradientColor(startColor, endColor, step) {
        startRGB = colorRgb(startColor);//转换为rgb数组模式
        startR = startRGB[0];
        startG = startRGB[1];
        startB = startRGB[2];

        endRGB = colorRgb(endColor);
        endR = endRGB[0];
        endG = endRGB[1];
        endB = endRGB[2];

        sR = (endR - startR) / step;//总差值
        sG = (endG - startG) / step;
        sB = (endB - startB) / step;

        var colorArr = [];
        for (var i = 0; i < step; i++) {
            //计算每一步的hex值
            var hex = colorHex('rgb(' + parseInt((sR * i + startR)) + ',' + parseInt((sG * i + startG)) + ',' + parseInt((sB * i + startB)) + ')');
            colorArr.push(hex);
        }
        return colorArr;
    }


    // 将hex表示方式转换为rgb表示方式(这里返回rgb数组模式)
    function colorRgb(sColor) {
        var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
        var sColor = sColor.toLowerCase();
        if (sColor && reg.test(sColor)) {
            if (sColor.length === 4) {
                var sColorNew = "#";
                for (var i = 1; i < 4; i += 1) {
                    sColorNew += sColor.slice(i, i + 1).concat(sColor.slice(i, i + 1));
                }
                sColor = sColorNew;
            }
            //处理六位的颜色值
            var sColorChange = [];
            for (var i = 1; i < 7; i += 2) {
                sColorChange.push(parseInt("0x" + sColor.slice(i, i + 2)));
            }
            return sColorChange;
            // return "RGB(" + sColorChange.join(",") + ")";
        } else {
            return sColor;
        }
    }

    // 将rgb表示方式转换为hex表示方式
    function colorHex(rgb) {
        var _this = rgb;
        var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
        if (/^(rgb|RGB)/.test(_this)) {
            var aColor = _this.replace(/(?:(|)|rgb|RGB)*/g, "").split(",");
            var bColor=[];
            bColor.push(aColor[0].slice(1),aColor[1],aColor[2].slice(0,-1));
            var strHex = "#";
            for (var i = 0; i < bColor.length; i++) {
                var hex = Number(bColor[i]).toString(16);
                // console.log(typeof (hex));
                //保证每个rgb的值为2位
                if(hex.length==1){
                    hex='0'+hex;
                }
                // hex = hex < 10 ?  0+'' + hex : hex;// 保证每个rgb的值为2位
                // if (hex === "0") {
                //     hex += hex;
                // }
                strHex += hex;
            }
            if (strHex.length !== 7) {
                strHex = _this;
            }
            return strHex;
        } else if (reg.test(_this)) {
            var aNum = _this.replace(/#/, "").split("");
            if (aNum.length === 6) {
                return _this;
            } else if (aNum.length === 3) {
                var numHex = "#";
                for (var i = 0; i < aNum.length; i += 1) {
                    numHex += (aNum[i] + aNum[i]);
                }
                return numHex;
            }
        } else {
            return _this;
        }

    }

    //构建热力图,_sensorIndex为某组传感器的父节点索引,whichAxis为该组传感器位于哪个轴,_partInex为相应的小块的父节点索引
    function heatMapFun(_sensorIndex,_partInex,whichAxis){

        var partX, partY, partZ,zsensorX, zsensorY, zsensorZ, zsensorT, distanceMin, distance = [],minIndex;
        var partMap = new Dictionary();//存放小块数据(索引+温度值 或 索引+颜色值)
        var part = sensor.children[0].children[0].children[3].children[5].children[6].children[_partInex];//小块父节点
        var zsensor;//传感器父节点
        //根据断各部件传感器所在轴，来确定其传感器组的父节点索引
        switch (whichAxis){
            case 'X':
                zsensor = sensor.children[0].children[0].children[3].children[_sensorIndex];
                break;
            case 'Y':
                zsensor = sensor.children[0].children[0].children[3].children[5].children[_sensorIndex];
                break;
            case 'Z':
                zsensor = sensor.children[0].children[0].children[3].children[5].children[6].children[_sensorIndex];
                break;
        }

        //1.传感器的点映射到小块上(即找到与当前传感器最近的小块)
        for (var i = 1; i < zsensor.children.length; i++) {
            zsensorX = zsensor.children[i].position.x;
            zsensorY = zsensor.children[i].position.y;
            zsensorZ = zsensor.children[i].position.z;

            //获取温度值
            var str = zsensor.children[i].name;
            var str1 = str.replace(/_/g, '-');
            var item = str1.substring(1);
            zsensorT = temMap.get(item);

            // 当温度值为0时，中断此次循环，表示当前传感器没有数据
            if(zsensorT==0){
                continue
            }

            minIndex = 1;
            distanceMin = Math.pow(part.children[1].position.x - zsensorX, 2)
                + Math.pow(part.children[1].position.y - zsensorY, 2)
                + Math.pow(part.children[1].position.z - zsensorZ, 2);

            for (var j = 1; j < part.children.length; j++) {

                partX = part.children[j].position.x;
                partY = part.children[j].position.y;
                partZ = part.children[j].position.z;

                distance[j] = Math.pow(partX - zsensorX, 2) + Math.pow(partY - zsensorY, 2) + Math.pow(partZ - zsensorZ, 2);
                if (distance[j] < distanceMin) {
                    distanceMin = distance[j];
                    minIndex = j;
                }
            }
            partMap.set(minIndex, zsensorT);
            // console.log(minIndex,item);
        }
        // console.log(partMap.getItems());


        //2.生成80个颜色值，分别对应20-100度
        var colorblock1=new gradientColor('#1FEDFF', '#00FFFF', 16);//20-35
        var colorblock2=new gradientColor('#00FFFF', '#00FF00', 15);//35-50
        var colorblock3=new gradientColor('#00FF00', '#FFFF00', 20);//50-70
        var colorblock4=new gradientColor('#FFFF00', '#FF0000', 30);//70-100

        var colorArray1=colorblock1.concat(colorblock2);
        var colorArray2=colorArray1.concat(colorblock3);
        var colorArray=colorArray2.concat(colorblock4);

        //生成图例
        var legend = document.getElementById("legend");
        for(var i=0;i<colorArray.length;i++){
            var span = document.createElement("span");
            span.style.width = "30px";
            span.style.height = "3px";
            span.style.position="absolute";
            span.style.bottom=i*3+"px";
            span.style.backgroundColor = colorArray[i];
            legend.appendChild(span);
        }
        for(var i=0;i<colorArray.length;i++){
            var span = document.createElement("span");
            span.style.width = "30px";
            span.style.height = "3px";
            span.style.position="absolute";
            span.style.bottom=i*3+"px";
            span.style.left="30px";

            switch (i) {
                case 0:
                    span.innerHTML="20";
                    break;
                case 15:
                    span.innerHTML="35";
                    break;
                case 30:
                    span.innerHTML="50";
                    break;
                case 50:
                    span.innerHTML="70";
                    break;
                case 80:
                    span.innerHTML="100";
                    break;
            }
            legend.appendChild(span);
        }


        //3.法1:采用绝对温度，20-100度 每个温度对应一个颜色值，给传感器对应的各个小块赋颜色
        //  法2:采用相对温度，归一化x=(x−min)/(max−min),0-1每个值对应一个颜色，给传感器对应的各个小块赋颜色
        var index = partMap.keys();//传感器对应的小块的索引
        var partTData = partMap.values();//相应小块的温度数据
        var tempMax, tempMin;//90个小块的最大值、最小值

        //（舍）求最大值最小值 归一化
        // tempMax = partTData[0];
        // tempMin = partTData[0];
        // for (var i = 0; i < partTData.length; i++) {
        //     if (partTData[i] > tempMax) {
        //         tempMax = partTData[i];
        //     }
        //     if (partTData[i] < tempMin) {
        //         tempMin = partTData[i];
        //     }
        // }

        for (var i = 0; i < index.length; i++) {
            // var normal = ((partTData[i] - tempMin) / (tempMax - tempMin)).toFixed(2);
            // var colorValue=colorArray[parseInt(normal*100)];

            if(Math.round(partTData[i])<20){
                partTData[i]=20
            }
            if(Math.round(partTData[i])>100){
                partTData[i]=100
            }
            var colorValue=colorArray[Math.round(partTData[i])-20];

            partMap.set(index[i], colorValue);//此后partMap存放:索引+颜色值
            part.children[index[i]].children[0].material.color.set(partMap.get(index[i]));
        }
        // console.log(partMap.getItems());

        //4.两个小块之间渐变色填充
        for (var i = 0; i <= index.length; i++) {
            var startColor,endColor,step,gradient=[];
            if(i==0){
                startColor=partMap.get(index[0]);
                endColor=partMap.get(index[i]);
                step=index[i]+1;//0-index[i]
                gradient= new gradientColor(startColor, endColor, step);

                for(var j=0;j<=index[i];j++){//从0开始
                    part.children[j].children[0].material.color.set(gradient[j]);
                }
            }
            else if(i==index.length){
                startColor=partMap.get(index[i-1]);
                endColor=partMap.get(index[index.length-1]);
                step=part.children.length-1-index[i-1];
                gradient= new gradientColor(startColor, endColor, step);

                for(var j=index[i-1]+1;j<part.children.length;j++){
                    part.children[j].children[0].material.color.set(gradient[j-index[i-1]-1]);
                }
            }
            else{
                startColor=partMap.get(index[i-1]);
                endColor=partMap.get(index[i]);
                step=index[i]-index[i-1];
                gradient= new gradientColor(startColor, endColor, step);

                for(var j=index[i-1]+1;j<=index[i];j++){
                    part.children[j].children[0].material.color.set(gradient[j-index[i-1]-1]);
                }
            }

        }
    }

</script>

</body>
</html>